<!--问答界面-->
<template>
  <div class="robot-tab-cont">
    <div class="robot-content">
      <div class="robot-type-content">
        <template v-for="presetKeywordsType in presetKeywordsTypes">
          <div class="robot-type-item">
            <div class="robot-type-item-title">
              <img :src="presetKeywordsType.imgName"/>
              {{presetKeywordsType.name}}
            </div>
            <div class="robot-type-item-con">
              <template v-for="keywords in presetKeywordsType.presetKeywords">
                <div class="robot-type-link" @click="simpleClick(keywords.question, keywords.queLevel, keywords.areas, keywords.bankNo, qaBankTypes[keywords.qaBankType])">{{keywords.showName}}</div>
              </template>
              </div>
          </div>
        </template>
      </div>
      <div class="windows_body2"><!--为了抵抗happy-scroll自动设置高宽-->
        <happy-scroll
            color="rgba(0,0,0,0.2)"
            size="10"
            :resize="true"
            smaller-move-v1="start"
            bigger-move-h1="end"
            :min-length-h="20"
            hide-horizontal>
          <ul class="newsList" id="chatbox">
            <template v-for="(record,tabIndex) in chatRecord">
              <!-- 开场语 -->
              <li v-if="record.type=='receive_0'" class="me">
                <div class="robot-time">{{ record.time | formatDateTime }}</div>
                <div class="answerHead">
                  <img src="../../assets/images/robot-manbig.png" :title="robot.robotName">
                  <p>{{ robot.robotName }}</p>
                </div>
                <div class="answers">
                  <i class="triangle"></i>
                  <div class="answers-text">
                    HI，您好，我是{{ robot.robotName }}，可为您提供法律咨询服务，你可以对我说
                    <a @click="selectQaBankType(qaBankTypes.complianceAdvice)" href="javascript:void(0)">{{qaBankTypes.complianceAdvice.name}}</a>
                    或者
                    <a @click="selectQaBankType(qaBankTypes.riskAtlas)" href="javascript:void(0)">{{qaBankTypes.riskAtlas.name}}</a>
                    ，也可以点击上面导航栏了解相关知识。
                  </div>
                </div>
              </li>
              <!-- 通过后台查询之后的回答 -->
              <li v-if="record.type=='receive_1'" class="me">
                <div class="answerHead userAnswer" :tabindex=tabIndex>
                  <img src="../../assets/images/robot-manbig.png" :title="robot.robotName">
                  <p>{{ robot.robotName }}</p>
                </div>
                <div class="answers">
                  <i class="triangle"></i>
                  <div :class="{'answers-text':true, 'has-label':record.showQaBankTypeName}">
                    <span class="tag-blue" v-if="record.showQaBankTypeName">
                      {{ record.msgSend }}
                    </span>
                    <div v-if="record.data.length === 0">
                      <span class="content2">
                        对不起，{{ robot.robotName }}还没学会，请点击<a :href="artificialUrl" target="_blank">人工咨询</a>
                      </span>
                    </div>
                    <div v-else-if="record.level===2">
                      <div v-if="record.msgSend==='合规领域'">
                        <!--我们合规领域主要有公司治理、反垄断、反不正当竞争、商业贿赂、商业秘密、信息安全、合作伙伴、知识产权、【二级目录中的合规领域】，请点击您感兴趣的领域-->
                        我们合规领域主要有
                        <template v-for="(answer,index) in record.data">
                          <a @click="simpleClick(answer.content, 2, answer.content)"
                             href="javascript:void(0)">{{ answer.content }}</a>
                          <span v-if="index + 1 < record.data.length">、</span>
                        </template>
                        ，请点击您感兴趣的领域
                      </div>
                      <div v-else-if="record.msgSend==='业务领域'">
                        <!--我们根据公司业务划分了九个业务领域，分别是【二级目录中的领域分类】、【二级目录中的领域分类】……..请点击您感兴趣的业务领域-->
                        我们根据公司业务划分了九个业务领域，分别是
                        <template v-for="(answer,index) in record.data">
                          <a @click="simpleClick(answer.content, 2, answer.content)"
                             href="javascript:void(0)">{{ answer.content }}</a>
                          <span v-if="index + 1 < record.data.length">、</span>
                        </template>
                        请点击您感兴趣的业务领域
                      </div>
                    </div>
                    <div v-else-if="record.level === 3">
                      <ul>
                        <li>您好，请问您是不是想要了解以下内容？</li>
                        <template v-for="answer in record.data">
                          <li><span class="queModuleTitle">【{{answer.areas}}】</span></li>
                          <template v-for="(content, index) in answer.showContents">
                            <li>
                              <a href="javascript:void(0)" @click="simpleClick(content, 3, answer.areas, null, record.qaBankType)">
                                <p class="indent" v-html="(index + 1) + '. ' + content"></p>
                              </a>
                            </li>
                          </template>
                        </template>
                        <li>
                          如以上都不是请点击
                          <a @click="moreQueName(record)" href="javascript:void(0)">更多</a>
                          或
                          <a :href="artificialUrl" target="_blank">人工咨询</a>
                        </li>
                      </ul>
                    </div>
                    <div v-else-if="record.level === 4">
                      <!--您好，关于xxxx（所选三级名称）小獬为您推荐了以下内容，请选择您感兴趣的内容点击查看。
                      什么是垄断协议？（四级）
                      什么是横向垄断协议？
                      如何避免达成横向垄断协议？
                      如以上都不是请点击【更多】【人工咨询】-->
                      <ul>
                        <li>您好，关于{{ record.msgSend }}{{robot.robotName }}为您推荐了以下内容，请选择您感兴趣的内容点击查看。</li>
                        <template v-for="(answer, index) in record.data">
                          <li>
                            <a @click="answerItemClick(answer, 4, record.qaBankType)"
                               href="javascript:void(0)" v-html="(index + 1) + '. ' + answer.content"
                            />
                          </li>
                        </template>
                        <li>
                          如以上都不是请点击
                          <a @click="moreQueName(record)" href="javascript:void(0)">更多</a>
                          或
                          <a :href="artificialUrl" target="_blank">人工咨询</a>
                        </li>
                      </ul>
                    </div>
                    <div v-else-if="record.level === 5">
                      <!--以下行为会被认为存在风险：
                          1.【五级目录】
                          2.【五级目录】
                          3【五级目录】
                          4（随着五级目录数量动态增加）。。。。
                          请问您需要进一步了解相关案例、责任后果、责任类型、责任主体、法律依据、合规建议么？如需要请点击具体行为。-->
                      以下行为会被认为存在风险：
                      <template v-for="(answer,index) in record.data">
                        <br/>
                        <a @click="answerItemClick(answer, 5, record.qaBankType)"
                           href="javascript:void(0)" v-html="(index + 1) + '. ' + answer.content"
                        />
                      </template>
                      请问您需要进一步了解相关案例、责任后果、责任类型、责任主体、法律依据、合规建议么？如需要请点击具体行为。
                    </div>
                    <div v-else-if="record.level === 0">
                      <!-- 2020-07-10 shenyi add 找不到答案时显示<span class=multiContent-dept>[部门专属]<span>-->
                      <span class="content2" v-if="record.data[0].answerType === '2'"
                            v-html="(record.data[0].content||'').replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, emotionToImg)"
                      />
                      <span class="content2" v-if="record.data[0].answerType === '3'">
                        {{record.data[0].content}}请点击<a :href="artificialUrl" target="_blank">人工咨询</a>
                      </span>
                    </div>
                    <div v-else-if="record.level === 6 && record.data.length === 1">
                      <template v-for="(answer,index) in record.data">
                        <ul :class="{ansContent:true, answerOverflow:record.answerOverflow}" >
                          <li v-if="answer.riskWarning">
                            <div><label>合规义务</label></div>
                            <div v-html="answer.riskWarning" :class="{riskAtlasOverflow:answer.hiddenOverRiskWarning}"></div>
                            <div v-show="answer.hiddenOverRiskWarning" class="clickMore">
                              <a @click="answer.hiddenOverRiskWarning = !answer.hiddenOverRiskWarning" href="javascript:void(0)">点击展开更多</a>
                            </div>
                          </li>
                          <li v-if="answer.respContent">
                            <div><label>违规责任</label></div>
                            <div v-html="answer.respContent" :class="{riskAtlasOverflow: answer.hiddenOverRespContent}"></div>
                            <div v-show="answer.hiddenOverRespContent" class="clickMore">
                              <a @click="answer.hiddenOverRespContent = !answer.hiddenOverRespContent" href="javascript:void(0)">点击展开更多</a>
                            </div>
                          </li>
                          <li v-if="answer.respPost">
                            <div><label>合规责任岗位</label></div>
                            <div v-html="answer.respPost"></div>
                          </li>
                          <li v-if="answer.supervisePost">
                            <div><label>合规监督岗位</label></div>
                            <div v-html="answer.supervisePost"></div>
                          </li>
                          <li v-if="answer.qaLawRegulationsList && answer.qaLawRegulationsList.length > 0">
                            <div><label>法律法规</label></div>
                            <div v-for="qa in answer.qaLawRegulationsList">
                              <a target="_blank" :href="qa.url">{{qa.name }}</a></div>
                          </li>
                          <li v-if="answer.managementSystem">
                            <div><label>管理制度</label></div>
                            <div v-html="answer.managementSystem"></div>
                          </li>
                          <li v-if="answer.qaComplianceAdviceList && answer.qaComplianceAdviceList.length > 0">
                            <div><label>合规指引</label></div>
                            <div v-for="qa in answer.qaComplianceAdviceList">
                              <a target="_blank" :href="qa.url">{{ qa.name }}</a>
                            </div>
                          </li>
                          <li v-if="answer.qaTypicalCaseList && answer.qaTypicalCaseList.length > 0">
                            <div><label>典型案例</label></div>
                            <div v-for="qa in answer.qaTypicalCaseList">
                              <a target="_blank" :href="qa.url">{{qa.name }}</a></div>
                          </li>
                          <li v-if="answer.associationNumber">
                            <div><label>风险全景图关联编号</label></div>
                            <div>{{ answer.associationNumber }}</div>
                          </li>
                          <li v-if="answer.questionAnswer">
                            <div v-html="answer.questionAnswer" :class="{complianceAdviceOverflow: answer.hiddenOverQuestionAnswer}"></div>
                            <div v-show="answer.hiddenOverQuestionAnswer" class="clickMore">
                              <a @click="answer.hiddenOverQuestionAnswer = !answer.hiddenOverQuestionAnswer" href="javascript:void(0)">点击展开更多</a>
                            </div>
                          </li>
                        </ul>
                      </template>
                    </div>
                    <div v-else>
                      <!--专业问题的多答案增加猜想提示-->
                      <ul>
                        <li><span>{{ robot.robotName }}</span>猜您想要咨询的问题是：</li>
                        <template v-for="(answer,index) in record.data">
                          <!-- 答案正文换行，多行专业答案允许单击后自动问答-->
                          <li>
                            <a :class="{'actived':answer.isActive,'multiContent':true}"
                               v-if="answer.answerType ==='1' && answer.content !== '' && answer.twoLevel !=='' "
                               href="javascript:void(0)"
                               @click="simpleClick(answer.content, record.level, answer.areas, answer.bankNo, record.qaBankType)"
                               v-html="(index + 1) + '、' + answer.content"
                            />
                          </li>
                        </template>
                      </ul>
                    </div>
                  </div>
                </div>

              </li>
              <!-- 切换为“合规职责”后说的第一个气泡 -->
              <li v-if="record.type=='receive_2'" class="me">
                <div class="answerHead userAnswer" :tabindex=tabIndex>
                  <img src="../../assets/images/robot-manbig.png" :title="robot.robotName">
                  <p>{{ robot.robotName }}</p>
                </div>
                <div class="answers">
                  <i class="triangle"></i>
                  <div class="answers-text has-label"><span class="tag-blue" >{{record.qaBankType.name}}</span>
                    <ul>
                      <li>您好，{{robot.robotName}}根据您的岗位情况为您匹配了以下合规职责</li>
                      <template v-for="(answer,index) in record.data">
                        <li>
                          <a @click="simpleClick(answer.queName, 4, answer.areas, answer.bankNo, qaBankTypes.riskAtlas)" href="javascript:void(0)">
                            {{index + 1}}、{{ answer.queName }}
                          </a>
                        </li>
                      </template>
                    </ul>
                  </div>
                </div>
              </li>
              <!-- 切换为“合规职责”后说的第二个气泡 -->
              <li v-if="record.type=='receive_3'" class="me">
                <div class="answerHead userAnswer" :tabindex=tabIndex>
                  <img src="../../assets/images/robot-manbig.png" :title="robot.robotName">
                  <p>{{ robot.robotName }}</p>
                </div>
                <div class="answers">
                  <i class="triangle"></i>
                  <div class="answers-text">
                    您还可以点击
                    <router-link :to="{path:'/panoramicList',query:{category: '按钮', title: '我的合规清单'}}" target="_blank">查看我的所有合规职责清单</router-link>
                    或者
                    <router-link :to="{path:'/panoramicList',query:{category: '按钮', title: '合规风险全景图'}}" target="_blank">查看所有岗位的合规职责清单</router-link>
                  </div>
                </div>
              </li>
              <!-- 切换为“我要咨询”后说的气泡 -->
              <li v-if="record.type=='receive_4'" class="me">
                <div class="answerHead userAnswer" :tabindex=tabIndex>
                  <img src="../../assets/images/robot-manbig.png" :title="robot.robotName">
                  <p>{{ robot.robotName }}</p>
                </div>
                <div class="answers">
                  <i class="triangle"></i>
                  <div class="answers-text">您好，请问您要咨询什么问题，可以直接在对话框输入您想要问的问题。</div>
                </div>
              </li>
              <!-- “我”的问题 -->
              <li v-if="record.type=='send'" class="other">
                <div class="robot-time">{{ record.time | formatDateTime }}</div>
                <div class="nesHead user">
                  <img :src="decode(userInfo.imageUrl)"
                       onerror="this.src='static/image/user.png'"
                       :title="userInfo.userName">
                  <p class="mytextR">{{ userInfo.userName }}</p>
                </div>
                <div class="news">
                  <i class="n-triangle"></i>
                  <p v-html="(record.data||'').replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, emotionToImg)"></p>
                </div>
              </li>
            </template>
          </ul>
        </happy-scroll>
      </div>
      <div class="input-box">
        <div style="float: left">
          <a href="javascript:void(0)" class="voice" @click="showEmotionBox">
            <i class="iconfont icon-biaoqing"/>&nbsp;
          </a>
        </div>
        <EmotionBox v-show="emotionBox" @emotion="emotionClick" class="meme" :height="130"/>
        <EmotionEditor v-model='msgToSend' @keyup.13.native="editorEnter"/>
        <div style="float: right">
          <button id="submit" @click="sendQuestion" class="btn btn-primary">发送</button>
        </div>

      </div>
    </div>
    <div class="robot-right">
      <!-- Swiper -->
      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide">
            <div class="hot-news">
              <h1><i class="iconfont icon-remen1"></i>热门搜索</h1>
              <ul>
                <li v-for="item in searchQuestions">
                  <a @click="hotQuestionClick(item, $event)" href="javascript:void(0)" :title="item.queName">
                    <span>•</span>{{ item.queName }}<br>
                  </a>
                </li>
              </ul>
            </div>
          </div>
          <div class="swiper-slide">
            <div class="hot-news">
              <h1><i class="iconfont icon-remen1"></i>热门推荐</h1>
              <ul>
                <li v-for="item in hotQuestions">
                  <a @click="hotQuestionClick(item, $event)" href="javascript:void(0)" :title="item.queName">
                    <span>•</span>{{ item.queName }}
                  </a>
                </li>
              </ul>
            </div>
          </div>
          <div class="swiper-slide">
            <div class="hot-news">
              <h1><i class="iconfont icon-remen1"></i>政策解读</h1>
              <ul>
                <li v-for="item in policyAnalyzingList">
                  <a @click="dialogVisible = true;dialogName = item.id" href="javascript:void(0)" :title="item.queName">
                    <span>•</span>{{ item.queName }}
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <!-- Add Pagination -->
        <div class="swiper-pagination"></div>
      </div>
      <!--      <div class="banner">
              <a href="javascript:void(0)"><img src="images/banner01.png"/></a>
            </div>-->
      <div class="banner">
        <router-link :to="{path:'/newPanorama'}" target="_blank">
          <div class="panorama-img"></div>
        </router-link>
      </div>
    </div>
    <div id="dialogV">
      <el-dialog :visible.sync="dialogVisible" width="0px">
        <div v-for="item in policyAnalyzingList">
          <div v-show="dialogName === item.id">
            <img :src="getPolicyAnalyzingImage(item.id)" width="600px"/>
          </div>
        </div>
      </el-dialog>
    </div>
    <div style="display: none" id="overFlowText"></div>
  </div>
</template>

<script>

import API from "components/api-chat-window";
import Qs from "qs";
import windowConst from "@/utils/const";
import EmotionBox from "components/emotion/EmotionBox";
import EmotionEditor from "components/emotion/EmotionEditor";
import { xssFilter } from "@/utils/xssFilter";
export default {
  components: {EmotionBox, EmotionEditor},
  props: {
    robot: {
      type: Object,
      default: {
        robotName: ""
      }
    },
    // 个人信息
    userAuths: {
      type: Array,
      default: []
    },
    talkSessionId:{
      type: String
    }
  },
  data() {
    return {
      willShowConfirm: false,
      // 问候语
      greetingMsg: "",
      // 人员权限
      userInfo: {},
      // 第一次回答
      talkAnswers_0: [],
      // 聊天记录
      chatRecord: [],
      // 要发送的消息
      msgToSend: "",
      // 热门问题
      hotQuestions: [],
      // 搜索问题排行
      searchQuestions: [],
      //政策解读
      policyAnalyzingList: [],
      dialogVisible: false,
      dialogName: "",
      // 点赞或踩
      upAndDown: {
        show: true,
        type: null,
        commnetId: ""
      },
      emotionBox: false,
      needEmotionBox: false,
      yhyjConfirmStatus: false,
      yhjy_form: {},
      rules: {
        title: [
          {required: true, message: '建议标题不能为空', trigger: 'change'}
        ], question: [
          {required: true, message: '请选择针对问题', trigger: 'change'}
        ],
      }, imgWinStatus: false,
      initModuleName: "",
      area: "",
      list: ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙',
        '惊讶', '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '可爱', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '大兵',
        '奋斗', '咒骂', '疑问', '嘘', '晕', '折磨', '衰', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼',
        '右哼哼', '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓', '咖啡',
        '饭', '猪头', '玫瑰', '凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳',
        '礼物', '拥抱', '强', '弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', '好的', '爱情', '飞吻', '跳跳',
        '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', '挥手', '激动', '街舞', '献吻', '左太极', '右太极'],
      mineRelationQueName: [],
      //随机抽取的数量
      randomNum: 3,
      qaBankTypes: {
        //风险图谱题库
        riskAtlas: {label: "riskAtlas", name: "我要了解合规职责", alias: "合规职责", hiddenLength: 150},
        //合规指引题库
        complianceAdvice: {label: "complianceAdvice", name: "我要咨询", alias: "咨询", hiddenLength: 250},
      },
      //当前题库类型
      currentQaBankType: {},
      //人工服务链接
      artificialUrl: "",
      // 是否开启过长隐藏的阈值
      hiddenLength: 200,
      // 预设关键字
      presetKeywordsTypes:[],
    }
  },
  created() {
    window.consult = this;
    this.currentQaBankType = this.qaBankTypes.complianceAdvice;
    this.artificialUrl = windowConst.VUE_APP_ARTIFICIAL_URL;
  },
  mounted() {
    const vue = this;

    API.findMineRelationQueName().then(res => {
      vue.mineRelationQueName = res.data;
    });

    vue.greetingMsg = vue.robot.openingWords;
    //推送开场语
    vue.chatRecord.push({
      type: "receive_0",
      time: new Date(),
      data: vue.greetingMsg
    });

    // 个人信息
    API.getUserInfo({}).then(res => {
      if (res.data) {
        vue.userInfo = res.data;
      }
    })
    // 热门问题
    API.getHotQuestions().then(res => {
      vue.hotQuestions = res.data;
    })
    // 热门搜索
    API.getSearchQuestions().then(res => {
      vue.searchQuestions = res.data;
    })
    // 政策解读
    API.getPolicyAnalyzingList().then(res => {
      vue.policyAnalyzingList = res.data;
      vue.policyAnalyzingList.forEach(function (value) {
        value.show = false;
      })
    })
    // 预设关键字
    API.getPresetKeyWordsTypes().then(res => {
      vue.presetKeywordsTypes = res.data;
    })


    //加载轮播图
    var swiper = new Swiper('.swiper-container', {
      pagination: '.swiper-pagination',
      // nextButton: '.swiper-button-next',
      // prevButton: '.swiper-button-prev',
      paginationClickable: true,
      spaceBetween: 30,
      centeredSlides: true,
      autoplay: 3000,
      autoplayDisableOnInteraction: false
    });
  },
  watch: {
    chatRecord(data, changeData) {
      let vue = this;
      vue.$nextTick(function () {
        let chatBox = document.getElementById("chatbox");
        chatBox.scrollTop = chatBox.scrollHeight
      })
    }
  },
  methods: {
    //定位焦点
    focusAnswer() {
      // 202212 翻到最下面
      document.getElementsByClassName("happy-scroll-container")[0].scrollTop = 999999;
    },
    // 发送问题
    sendQuestion(level = 0, areas = '', bankNo = '', qaBankType = this.currentQaBankType) {
      if (typeof level != 'number') {
        //用户搜索时可能会发送成其他数据
        level = 0;
      }
      const vue = this;
      const msgSend = xssFilter(vue.msgToSend && vue.msgToSend.trim())
      const l = msgSend.length;
      if (l > 200) {
        this.$message.error("发送的内容不能超过200个字符");
        return
      }
      if (msgSend == null || msgSend.length == 0) {
        this.$message.error("不能发送空内容");
        vue.msgToSend = ""
        return
      }
      if(vue.isSendQaBankType(msgSend)){
        vue.msgToSend = null;
        return ;
      }

      // 发送聊天记录
      vue.chatRecord.push({
        type: "send",
        data: msgSend,
        time: new Date()
      });

      vue.upAndDown.show = true;
      vue.upAndDown.commnetId = null;
      vue.upAndDown.type = null;
      let queLabel;
      // 显示满意度
      vue.willShowConfirm = true;
      // 问答
      API.getTalkAnswers(Qs.stringify({
        type: 1,
        queName: msgSend,
        queLabel: queLabel,
        qaBankType: qaBankType.label,
        level: level,
        areas: areas,
        bankNo: bankNo,
        robotName: vue.robot.robotName || '',
        talkSessionId: vue.talkSessionId
      })).then(res => {
        if (!res.result) {
          return
        }
        const responseData = res.data instanceof Array ? res.data : [{content: res.data}];
        const data = responseData.slice(0, vue.randomNum);
        const level = res.nextLevel || 0;
        level === 3 && data.forEach(this.moreQueModule);
        level === 6 && this.hiddenOverData(responseData);

        vue.chatRecord.push({
          time: res.resTime,
          type: "receive_1",
          level: level,
          msgSend: msgSend,
          data: data,
          responseData: responseData,
          qaBankType: qaBankType,
          showQaBankTypeName: vue.showQaBankTypeName(data, level)
        });

        this.$nextTick(this.focusAnswer);
      });
      this.$nextTick(() => {
        //vue.msgToSend = null;
        //2020-06-30 shenyi 增加 发送问题后焦点定位到问题
        let questionObjs = document.getElementsByClassName("user");
        let n = questionObjs.length;
        n > 0 && (function () {
          questionObjs[n - 1].focus();
          questionObjs[n - 1].removeAttribute("tabindex");
        })();
        setTimeout(() => {
          document.getElementById("robot-emotion-box").focus();
        }, 500);
        vue.msgToSend = null;
      })
      return true;
    },
    // 回答点击
    answerItemClick(answer, level, qaBankType) {
      const vue = this;
      //2020-07-01 shenyi add 选中问题后 改变背景色
      if (typeof (answer) != "string") {
        answer.isActive = true;
        if (vue.answerActived) {
          vue.answerActived.isActive = false;//设置前一个选中取消背景
        }
        vue.answerActived = answer;//记录当前选中的问题
        vue.msgToSend = answer.content;
      } else {
        vue.msgToSend = answer;
      }
      vue.sendQuestion(level, answer.areas, answer.bankNo, qaBankType);
    },
    // 热门点击
    hotQuestionClick(question, e) {
      e.preventDefault();
      const vue = this;
      vue.msgToSend = question.queName;
      vue.sendQuestion()
    },
    // 简单点击
    simpleClick(question, level, areas, bankNo, qaBankType) {
      const vue = this;
      vue.msgToSend = question;
      vue.sendQuestion(level, areas, bankNo, qaBankType)
    },
    decode(url) {
      if (url) {
        return unescape(url.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1'));
      }
      return "";
    },
    editorEnter(event) {
      if (event && event.target) {
        event.target.blur()
        event.target.parentElement.focus()
        event.target.focus();
      }
      setTimeout(() => {
        this.sendQuestion();
      }, 1);
    },
    emotionClick(emotionCode) {
      this.msgToSend += emotionCode
      this.emotionBox = false;
    },
    // 将匹配结果替换表情图片
    emotionToImg(res) {
      res = res || ''
      let word = res.replace(/[#;]/gi, '')
      let index = this.list.indexOf(word)
      if (index > -1) {
        return `<img src="static/image/wx/${index}.gif"  data-code="${word}"  align="middle"/>`
      }
    },
    showEmotionBox() {//2020-07-24 shenyi add 显示表情包
      this.needEmotionBox = true;
      this.emotionBox = !this.emotionBox;
      this.$nextTick(() => {
        setTimeout(() => {
          this.needEmotionBox = false;
        }, 200);

      })
    },
    hideEmotionBox() {//2020-07-24 shenyi add 点击其它位置隐藏表情包
      if (!this.needEmotionBox) {
        this.emotionBox = false;
      }
    },
    getPolicyAnalyzingImage(id) {
      return `${windowConst.VUE_APP_API_HOST}/api/findPolicyAnalyzingById.htm?id=${id}`;
    },
    //展开/折叠并跳转到指定高度
    changeAndFocus(answer, show, event) {
      answer[show] = !answer[show];
      if (answer[show]) {
        event.target.setAttribute("id", "tabIndex2");
        //此处不能立即获取高度，因为有数据展开折叠了，获取的会是过期的
        setTimeout(() => {
          let parentNode1 = document.getElementById("tabIndex2").parentNode.parentNode.parentNode;
          let parentNode2 = parentNode1.parentNode.parentNode.parentNode.parentNode.parentNode;

          document.getElementsByClassName("happy-scroll-container")[0].scrollTop
              = parentNode1.offsetTop + parentNode2.offsetTop;
          event.target.removeAttribute("id");
        }, 300);
      }
    },
    getRandomArray(arr, num) {
      //新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
      var temp_array = new Array();
      for (var index in arr) {
        temp_array.push(arr[index]);
      }
      //取出的数值项,保存在此数组
      var return_array = new Array();
      for (var i = 0; i < num; i++) {
        //判断如果数组还有可以取出的元素,以防下标越界
        if (temp_array.length > 0) {
          //在数组中产生一个随机索引
          var arrIndex = Math.floor(Math.random() * temp_array.length);
          //将此随机索引的对应的数组元素值复制出来
          return_array[i] = temp_array[arrIndex];
          //然后删掉此索引的数组元素,这时候temp_array变为新的数组
          temp_array.splice(arrIndex, 1);
        } else {
          //数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
          break;
        }
      }
      return return_array;
    },
    //判断是否为题库
    isSendQaBankType(msgSend){
      const qaBankTypes = this.qaBankTypes;
      for (let key in this.qaBankTypes) {
        const qaBankType = qaBankTypes[key];
        if(qaBankType.name === msgSend || qaBankType.alias === msgSend){
          this.selectQaBankType(qaBankType, msgSend);
          return true;
        }
      }
      return false;
    },
    //点击题库类型
    selectQaBankType(qaBankType, msgSend){
      const vue = this;
      this.currentQaBankType = qaBankType;
      // 发送聊天记录
      vue.chatRecord.push({
        type: "send",
        data: msgSend || qaBankType.name,
        time: new Date()
      });
      if (qaBankType === this.qaBankTypes.riskAtlas) {
        //随机几条
        const randomArray = vue.getRandomArray(vue.mineRelationQueName, vue.randomNum)
        vue.chatRecord.push({
          type: "receive_2",
          qaBankType: qaBankType,
          data: randomArray
        });
        vue.chatRecord.push({
          type: "receive_3"
        });
      } else {
        vue.chatRecord.push({
          type: "receive_4"
        });
      }
      this.$nextTick(this.focusAnswer);
    },
    // 点击更多问题题干
    moreQueName(record){
      const length = record.data.length;
      record.data = record.responseData.slice(0, length + this.randomNum);
      record.level === 3 && record.data.forEach(this.moreQueModule);
      this.$nextTick(this.focusAnswer);
    },
    //问题模块特殊处理
    moreQueModule(answer){
      const length = (answer.showContents && answer.showContents.length) || 0;// 第一次进来可能没有showContents字段
      answer.contents = answer.contents || [answer.content];
      answer.showContents = answer.contents.slice(0, length + this.randomNum);
    },
    showQaBankTypeName(data, level){
      return data.length > 0 && level > 0;
    },
    hiddenOverData(data){
      const vue = this;
      data.forEach(function (answer) {
        answer.hiddenOverRiskWarning = vue.wantHide(answer.riskWarning, vue.qaBankTypes.riskAtlas.hiddenLength);
        answer.hiddenOverRespContent = vue.wantHide(answer.respContent, vue.qaBankTypes.riskAtlas.hiddenLength);
        answer.hiddenOverQuestionAnswer = vue.wantHide(answer.questionAnswer, vue.qaBankTypes.complianceAdvice.hiddenLength);
      })
    },
    //判断文本是否大于阈值
    //往隐藏域中填充html，再取数其中的text
    wantHide(html, hiddenLength){
      const overFlowText = document.querySelector("#overFlowText")
      overFlowText.innerHTML = html;
      const isOver = overFlowText.innerText.length > hiddenLength;
      overFlowText.innerHTML = "";
      return isOver;
    },
  },
  filters: {
    formatDateTime(value) {
      if (typeof (value) == "string") {
        value = value.replace(/-/g, "/");
      }
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "年" + MM + "月" + d + "日 " + h + ":" + m + ":" + s;
    },
  }
}
</script>